"""简化的消息处理器"""
import json
import threading
import time
from .config import setup_logging

class MessageProcessor:
    """统一的消息处理器"""
    
    def __init__(self, connection_manager, media_processor):
        self.conn = connection_manager
        self.media = media_processor
        self.logger = setup_logging('Message')
        
        # 状态管理
        self.identity_confirmed = False
        self.confirmation_lock = threading.Lock()
        
        # 消息处理映射
        self.handlers = {
            'audio': self._handle_audio,
            'video': self._handle_video,
            'text': self._handle_text,
            'route': self._handle_route
        }
    
    def process_message(self, message):
        """处理接收到的消息"""
        if not isinstance(message, dict):
            self.logger.error(f"无效消息格式: {message}")
            return False
        
        msg_type = message.get('type')
        if not msg_type:
            self.logger.error("消息缺少类型字段")
            return False
        
        handler = self.handlers.get(msg_type)
        if handler:
            try:
                return handler(message)
            except Exception as e:
                self.logger.error(f"处理{msg_type}消息失败: {e}")
                return self._send_confirmation('failed', msg_type)
        else:
            self.logger.warning(f"未知消息类型: {msg_type}")
            return self._send_confirmation('failed', msg_type)
    
    def _handle_audio(self, message):
        """处理音频消息"""
        content = message.get('content')
        if not content:
            self.logger.error("音频消息缺少内容")
            return self._send_confirmation('failed', 'audio')
        
        # 保存音频内容
        filepath = self.media.save_media_content(content, 'audio')
        if filepath:
            self.logger.info(f"音频已保存: {filepath}")
            return self._send_confirmation('success', 'audio')
        else:
            return self._send_confirmation('failed', 'audio')
    
    def _handle_video(self, message):
        """处理视频消息"""
        content = message.get('content')
        if not content:
            self.logger.error("视频消息缺少内容")
            return self._send_confirmation('failed', 'video')
        
        # 保存视频内容
        filepath = self.media.save_media_content(content, 'video')
        if filepath:
            self.logger.info(f"视频已保存: {filepath}")
            return self._send_confirmation('success', 'video')
        else:
            return self._send_confirmation('failed', 'video')
    
    def _handle_text(self, message):
        """处理文本消息"""
        content = message.get('content', '')
        self.logger.info(f"收到文本消息: {content}")
        return self._send_confirmation('success', 'text')
    
    def _handle_route(self, message):
        """处理路线消息"""
        start = message.get('start', '')
        end = message.get('end', '')
        self.logger.info(f"收到路线消息: 从{start}到{end}")
        return self._send_confirmation('success', 'route')
    
    def send_text_message(self, content):
        """发送文本消息"""
        message = {
            "type": "text",
            "role": "hardware",
            "content": content
        }
        
        if self.conn.send_json(message):
            self.logger.info(f"文本消息已发送: {content}")
            return self._wait_for_confirmation()
        return False
    
    def send_audio_message(self, audio_data):
        """发送音频消息"""
        message = {
            "type": "audio",
            "role": "hardware"
        }
        
        if self.conn.send_json(message):
            self.logger.info("音频消息已发送")
            return self._wait_for_confirmation()
        return False
    
    def send_video_message(self, video_data):
        """发送视频消息"""
        message = {
            "type": "video",
            "role": "hardware"
        }
        
        if self.conn.send_json(message):
            self.logger.info("视频消息已发送")
            return self._wait_for_confirmation()
        return False
    
    def send_route_message(self, start, end):
        """发送路线消息"""
        message = {
            "type": "route",
            "role": "hardware",
            "start": start,
            "end": end
        }
        
        if self.conn.send_json(message):
            self.logger.info(f"路线消息已发送: {start} -> {end}")
            return self._wait_for_confirmation()
        return False
    
    def _send_confirmation(self, status, msg_type=None):
        """发送确认消息"""
        confirmation = {
            "type": "confirmation",
            "role": "hardware",
            "status": status,
            "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S")
        }
        
        if msg_type:
            confirmation["message_type"] = msg_type
        
        success = self.conn.send_json(confirmation)
        if success:
            self.logger.info(f"确认消息已发送: {status}")
            
            # 如果确认成功且身份未确认，则设置身份确认状态
            if status == 'success' and not self.identity_confirmed:
                with self.confirmation_lock:
                    self.identity_confirmed = True
                    self.logger.info("身份确认成功")
        
        return success
    
    def _wait_for_confirmation(self, timeout=5):
        """等待服务器确认"""
        try:
            response = self.conn.receive_and_confirm(timeout)
            if response and response.get('type') == 'confirmation':
                status = response.get('status')
                self.logger.info(f"收到确认: {status}")
                return status == 'success'
        except Exception as e:
            self.logger.error(f"等待确认失败: {e}")
        return False
    
    def send_identity_confirmation(self):
        """发送身份确认"""
        message = {
            "type": "connect",
            "role": "hardware",
            "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S")
        }
        
        if self.conn.send_json(message):
            self.logger.info("身份确认消息已发送")
            return self._wait_for_confirmation()
        return False
    
    def is_identity_confirmed(self):
        """检查身份是否已确认"""
        with self.confirmation_lock:
            return self.identity_confirmed
    
    def receive_message(self, timeout=1):
        """接收并处理消息"""
        try:
            message = self.conn.receive_and_confirm(timeout)
            if message:
                return self.process_message(message)
        except Exception as e:
            self.logger.error(f"接收消息失败: {e}")
        return False